dojo.require("dijit.dijit"); // optimize: load dijit layer
dojo.require("dojo.data.ItemFileWriteStore");
dojo.require("dijit.Dialog");
dojo.require("dojox.grid.DataGrid");
dojo.require("dojo.parser"); // scan page for widgets

var load_finished_interval;
var n_deleted=0;

dojo.addOnLoad( function()
{
	dialog_wait.closeButtonNode.style.display = "none";
	
	// hide loading gif
	window.setTimeout(function()
	{
		document.getElementById('img').style.display='none';
		document.getElementById('form').style.visibility='';
	}, 100);
	
	load_finished_interval = window.setInterval(function() {
		if (store_leaves._loadFinished == true)
		{
			load_finished();
			window.clearInterval(load_finished_interval);
		}
	}, 30);
});

var load_finished = function()
{
	if (store_leaves._arrayOfAllItems.length-n_deleted == 0)
	{
		window.setTimeout(function() { dialog_empty.show(); }, 200);
	}
};

var format_options = function(st)
{
	var r ='';
	r += '<button class="btn_accept" onClick="btn_click('+arguments[1]+', \'accept\')">&nbsp;</button>';
	r += '<button class="btn_deny" onClick="btn_click('+arguments[1]+', \'deny\')">&nbsp;</button>';
	return r;
};

var btn_click = function(rowIndex, opt)
{
	var itm = grid_leaves.getItem(rowIndex);
	submit_btn(
		store_leaves.getValue(itm, "account").replace(/@/, '%40')
		, store_leaves.getValue(itm, "start")
		, store_leaves.getValue(itm, "end")
		, opt, rowIndex
	);
};

var submit_btn = function(acc, start, end, opt, rowIndex)
{
	dialog_wait.show();
	dojo.xhrGet({
		url: "html?action=del&start="+start+"&end="+end+"&mdl=leave_requests&opt="+opt+"&acc="+acc,
	    handleAs: "text",
	    // timeout: 30000, infinity
	    load: function(rdata, ioArgs) {
			var itm = grid_leaves.getItem(rowIndex);
			store_leaves.deleteItem(itm);
			dialog_wait.hide();
			if (rdata != 'null')
			{
				alert ("Error while saving data. Please try again later. ("+rdata+")");
			}
			n_deleted++;
			load_finished();
	        return rdata;
	    },
	    error: function(response, ioArgs) {
	    	alert ("Error while saving data. Please try again later. ("+arguments[0]+")");
	    	dialog_wait.hide();
	        return response;
	    }
	});
};
